﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Extension
{
    // 可穿透的点击组件
    public class Clickable : MonoBehaviour, IPointerClickHandler
    {
        public Action m_onClick;
        
        // 记录上一次穿透事件的帧序号，防止循环调用陷入死循环
        int m_lastPassFrame;

        private void Awake()
        {
            m_lastPassFrame = -1;
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            if (m_lastPassFrame == Time.frameCount)
            {
                return;
            }
            
            m_onClick?.Invoke();
            
            m_lastPassFrame = Time.frameCount;
            PassEvent(eventData, ExecuteEvents.pointerClickHandler);
        }
    
        private void PassEvent<T>(PointerEventData data, ExecuteEvents.EventFunction<T> function) where T : IEventSystemHandler
        {
            List<RaycastResult> results = new List<RaycastResult>();
            EventSystem.current.RaycastAll(data, results); 
            //GameObject current = data.pointerCurrentRaycast.gameObject;
            for(int i = 0; i < results.Count; i++)
            {
                //Debug.Log($"--{results[i].gameObject.name}");
                if(results[i].gameObject != gameObject)
                {
                    ExecuteEvents.Execute(results[i].gameObject, data, function);

                    break;
                }
            }
            
        }
    }
    

}